package com.hoow.shakoow.shake

import android.annotation.SuppressLint
import android.os.*
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.android.billingclient.api.*
import com.hoow.shakoow.R
import com.hoow.shakoow.ai.data.ReqAiBase
import com.hoow.shakoow.ai.data.ReqSavePayOrderInfo
import com.hoow.shakoow.ai.home.NetworkViewModel
import com.hoow.shakoow.base.BaseActivity
import com.hoow.shakoow.databinding.ActivityUserRechargeBinding
import com.hoow.shakoow.enums.PageTagEnum
import com.hoow.shakoow.extend.*
import com.hoow.shakoow.shake.payBilling.PayBillingManager
import com.hoow.shakoow.shake.payBilling.PayBillingProcessListener
import com.hoow.shakoow.utils.analytics.util.AnalyticsUtil


/** 用户充值页 */
@SuppressLint("CustomSplashScreen")
class UserRechargeActivity : BaseActivity() {

    //布局binding
    private lateinit var mActivityBinding: ActivityUserRechargeBinding

    //布局binding
    private lateinit var mPayBillingManager: PayBillingManager

    //api接口viewModel
    private val mNetworkViewModel by lazy {
        ViewModelProvider(this)[NetworkViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mNetworkViewModel)
        return list
    }

    override fun onBindingViewTag(): String {
        return PageTagEnum.vip_info.name.uppercase()
    }

    override fun onBindingContentView(): View {
        mActivityBinding = ActivityUserRechargeBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("SetTextI18n", "SourceLockedOrientationActivity")
    override fun onContentViewBinded() {
        try {
            // 初始化支付模块
            mPayBillingManager = PayBillingManager(this)
            mPayBillingManager.setPayBillingListener(object : PayBillingProcessListener {
                override fun onCanPurchaseNow() {
                    runOnUiThread {
                        // 开始购买新的订单
                        mPayBillingManager.startNewPurchased()
                    }
                }

                override fun onPayPurchased(purchaseToken: String, purchaseOrderId: String) {
                    // 保存支付信息
                    runOnUiThread {
                        savePayOrderProcessInfo(purchaseToken, purchaseOrderId)
                    }
                }

                override fun onPayConsumed(purchaseToken: String, purchaseOrderId: String) {
                    // 支付与消耗成功
                    runOnUiThread {
                        savePayOrderSuccessInfo(purchaseToken, purchaseOrderId)
                    }
                }

                override fun onPrintLog(lineText: String) {
                    // 日志回调
                    printLog(lineText)
                }
            })

            // 初始化下拉刷新
            mActivityBinding.srlLayout.buildRefreshConfigs(this) {
                // 获取用户详情
                mNetworkViewModel.getUserVipInfo(ReqAiBase(showLoading = false))

                // 初始化支付
                mNetworkViewModel.getPayOrderId(ReqAiBase(showLoading = false))
            }

            //获取用户详情回调
            mNetworkViewModel.onGetUserVipInfoLiveData.observe(this) {
                mActivityBinding.srlLayout.isRefreshing = false

                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        mActivityBinding.textUserDaysAfterRechargeValue.text =
                            result.afterRemindDays
                        mActivityBinding.textUserDaysRemaingValue.text = result.currRemindDays
                        mActivityBinding.textUserMonthlyMembershipValue.text = result.monthPrice
                        mActivityBinding.textRechargeAmountValue.text =
                            getString(R.string.shake_you_will_pay, result.monthPrice)
                    }
                }
            }

            // 获取商品id返回
            mNetworkViewModel.onGetPayOrderIdLiveData.observe(this) {
                mActivityBinding.srlLayout.isRefreshing = false

                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        mNetworkViewModel.mPayOrderId = result.productId
                        mNetworkViewModel.mPayBuyId = result.buyId

                        // 查询购买历史
                        mPayBillingManager.queryPurchaseHistory()
                    }
                }
            }

            // 保存支付信息返回
            mNetworkViewModel.onSavePayOrderInfoLiveData.observe(this) {
                mActivityBinding.srlLayout.isRefreshing = false
                printLog("保存支付信息返回")
            }

            // 支付成功返回
            mNetworkViewModel.onPayOrderInfoSuccessLiveData.observe(this) {
                mActivityBinding.srlLayout.isRefreshing = false
                printLog("支付成功返回")

                if (it.isSuccess) {
                    Toast.makeText(this, "Pay success", Toast.LENGTH_SHORT).show()
                    printLog("确认支付成功")
                }
                // 获取用户详情
                mNetworkViewModel.getUserVipInfo(ReqAiBase())
            }

            // 获取用户详情
            mNetworkViewModel.getUserVipInfo(ReqAiBase())

            var isFirstStep = false
            // 点击购买
            mActivityBinding.textRechargeNow.rlBuyWithGooglePay.setOnClickListener {
                printLog("PBL->startConnection")
//                if (mNetworkViewModel.mPayBuyId.isBlank()) {
//                    // 初始化支付
//                    mNetworkViewModel.getPayOrderId(ReqAiBase())
//                } else {
//                    // 查询购买历史
//                    mPayBillingManager.queryPurchaseHistory()
//                }

                // 初始化支付
                mNetworkViewModel.getPayOrderId(ReqAiBase())

                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "START_BUY_CLICK",
                    remark = ""
                )
            }

            // 初始化支付
            // mNetworkViewModel.getPayOrderId(ReqAiBase())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
    }

    // 输出日志
    private fun printLog(text: String) {
//        runOnUiThread {
//            val preText = mActivityBinding.textRechargeNowLogs.text
//            val curText = "$preText\n$text"
//            mActivityBinding.textRechargeNowLogs.text = curText
//        }
    }

    // 保存支付信息
    private fun savePayOrderProcessInfo(pToken: String, pOrderId: String?) {
        printLog("Activity->savePayOrderProcessInfo: $pToken  $pOrderId")

        if (pToken.isNotBlank()) {
            mNetworkViewModel.savePayOrderInfo(
                ReqSavePayOrderInfo(
                    purchaseToken = pToken,
                    purchaseOrderId = pOrderId ?: "",
                    buyId = mNetworkViewModel.mPayBuyId
                )
            )
        }
    }

    // 保存支付成功
    private fun savePayOrderSuccessInfo(pToken: String, pOrderId: String?) {
        printLog("Activity->savePayOrderSuccessInfo: $pToken  $pOrderId")

        if (pToken.isNotBlank()) {
            mNetworkViewModel.payOrderInfoSuccess(
                ReqSavePayOrderInfo(
                    purchaseToken = pToken,
                    purchaseOrderId = pOrderId ?: "",
                    buyId = mNetworkViewModel.mPayBuyId
                )
            )
        }
    }
}